package common

import (
	"crypto/md5"
	"e_mall_server/config"
	"encoding/hex"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"math/rand"
	"mime/multipart"
	"os"
	"strconv"
	"time"
)

/**
 * @Author: zhaobin
 * @Description TODO
 * @Date: 2022-04-25 21:58
 */

// Md5 进行md5加密
func Md5(password string) (result string) {
	h := md5.New()
	h.Write([]byte(password))
	return hex.EncodeToString(h.Sum(nil))
}

// GetDay 获取年月日
func GetDay() string {
	template := "20060102"
	return time.Now().Format(template)
}

// GetUnixNano 获取纳秒
func GetUnixNano() int64 {
	return time.Now().UnixNano()
}

// OssUpload Oss上传图片
func OssUpload(file *multipart.FileHeader, dst string) (string, error) {

	f, err := file.Open()
	if err != nil {
		return "", err
	}
	defer f.Close()

	// 创建OSSClient实例。
	client, err := oss.New(config.Conf.Endpoint, config.Conf.AccessKeyId, config.Conf.AccessKeySecret)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 获取存储空间。
	bucket, err := client.Bucket(config.Conf.Bucket)
	if err != nil {
		return "", err
	}

	// 上传文件流。
	err = bucket.PutObject(dst, f)
	if err != nil {
		return "", err
	}
	return "https://" + config.Conf.Bucket + "." + config.Conf.Endpoint + "/" + dst, nil
}

//生成随机数
func GetRandomNum() string {
	var str string
	for i := 0; i < 4; i++ {
		current := rand.Intn(10)
		str += strconv.Itoa(current)
	}
	return str
}

// GetOrderId 生成订单id
func GetOrderId() string {
	// 2022020312233
	template := "20060102150405"
	return time.Now().Format(template) + GetRandomNum()
}
